package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.android.kotlincoroutinemvvmdemo.R
import com.android.kotlincoroutinemvvmdemo.util.LogX

class UnderStandardView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : View(context, attributeSet) {

    private var defaultWidth: Int = 0
    private var defaultHeight: Int = 0

    init {
        context.obtainStyledAttributes(attributeSet,R.styleable.UnderStandardView).apply {
            defaultWidth = getDimension(
                R.styleable.UnderStandardView_unspecified_width,
                context.resources.getDimension(R.dimen.dp_100)
            ).toInt()

            defaultHeight = getDimension(
                R.styleable.UnderStandardView_unspecified_height,
                context.resources.getDimension(R.dimen.dp_100)
            ).toInt()

            recycle()
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)

        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)

        val finalWidth = when (widthMode) {
            MeasureSpec.EXACTLY -> {
               LogX.d(TAG, "W-MeasureSpec.EXACTLY")
               widthSize
            }
            MeasureSpec.AT_MOST -> {
                LogX.d(TAG, "W-MeasureSpec.AT_MOST")
                defaultWidth.coerceAtMost(widthSize)
            }
            else -> {
                LogX.d(TAG, "W-MeasureSpec.UNSPECIFIED")
                defaultWidth
            }
        }

        val finalHeight = when (heightMode) {
            MeasureSpec.EXACTLY -> {
               LogX.d(TAG, "H-MeasureSpec.EXACTLY")
               heightSize  // 指定具体的高度
            }
            MeasureSpec.AT_MOST -> {
                LogX.d(TAG, "H-MeasureSpec.AT_MOST")
                defaultHeight.coerceAtMost(heightSize) // 不能超过父视图指定的最大高度
            }
            else -> {
                LogX.d(TAG, "H-MeasureSpec.UNSPECIFIED")
                defaultHeight  //自定义视图的高度
            }
        }

        setMeasuredDimension(finalWidth, finalHeight)
    }

    companion object {
        const val TAG = "UnderStandardView"
    }
}